package com.platform.api;

import com.baomidou.mybatisplus.mapper.Condition;
import com.platform.annotation.LoginUser;
import com.platform.dao.ApiCallUserBillMapper;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.utils.Query;
import com.platform.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 视频通话记录Controller
 *
 * @author zhurusen
 * @email 524227263@qq.com
 * @date 2018-05-15 15:50:14
 */
@RestController
@RequestMapping("api/call")
public class ApiCallController {
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiCallBillService apiCallBillService;
    @Autowired
    private ApiCallUserBillService apiCallUserBillService;
    @Autowired
    private ApiOrderService apiOrderService;
    @Autowired
    private ApiAmountBillService apiAmountBillService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    public R list(@LoginUser UserVo loginUser, @RequestParam(value = "page", defaultValue = "1") Integer page) {
        //查询列表数据
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", 10);
        params.put("userId", loginUser.getId());

        params.put("sidx", "create_time");
        params.put("order", "desc");
        Query query = new Query(params);

        List<ApiCallBillVo> list = apiCallBillService.selectList(query);


        List<Map<String, Object>> relist = new ArrayList<>();


        for (ApiCallBillVo info : list) {

            Map<String, Object> map = new HashMap<>();

            if (loginUser.getId().equals(info.getConsumer())) {
                /**
                 * 会员
                 */
                UserVo userVo = apiUserService.queryObject(info.getTvAnchor());

                Map<String, Object> userMap = new HashMap<>();
                userMap.put("userId", userVo.getId());
                userMap.put("avatar", userVo.getAvatar());
                userMap.put("nickName", userVo.getNickname());
                userMap.put("livePrice", userVo.getLive_price());
                userMap.put("mobile", userVo.getMobile());
                userMap.put("availableAmount", userVo.getAvailable_amount());

                map.put("createTime", info.getCreateTime());
                map.put("status", info.getStatus());
                map.put("talkTime", info.getTalkTime());
                map.put("userInfo", userMap);
                map.put("mode", info.getMode());
                map.put("remark", "(支出" + info.getConsumption().intValue() + "窝币)");

            }
            if (loginUser.getId().equals(info.getTvAnchor())) {
                /**
                 * 主播
                 */
                UserVo userVo = apiUserService.queryObject(info.getConsumer());
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("userId", userVo.getId());
                userMap.put("avatar", userVo.getAvatar());
                userMap.put("nickName", userVo.getNickname());
                userMap.put("livePrice", userVo.getLive_price());
                userMap.put("mobile", userVo.getMobile());
                userMap.put("availableAmount", userVo.getAvailable_amount());
                map.put("talkTime", info.getTalkTime());
                map.put("createTime", info.getCreateTime());
                map.put("status", info.getStatus());
                map.put("userInfo", userMap);
                map.put("mode", info.getMode() == 1 ? 2 : 1);
                map.put("remark", "(收入" + info.getConsumption().multiply(new BigDecimal(0.5)).intValue() + "窝币)");
            }
            relist.add(map);
        }

        return R.ok(0, "获取成功", relist);
    }


    /**
     * 每分钟生成一条通话记录
     *
     * @param loginUser
     * @param tvAnchor  接电话的人
     * @param consumer  打电话的人
     * @param callNo    序号
     * @param mode      1拨出   2 接听
     * @return
     */
    @RequestMapping("/addbill")
    public R addbill(@LoginUser UserVo loginUser, Long tvAnchor, Long consumer, String callNo, Integer mode, Long orderId) {

        loginUser = apiUserService.queryObject(loginUser.getId());

        UserVo userInfo = new UserVo();
        if (mode == 1) {
            userInfo = apiUserService.queryObject(tvAnchor);
        }
        if (mode == 2) {
            userInfo = apiUserService.queryObject(consumer);
        }


        if (userInfo != null) {

//            切换状态 1在线  2在聊 3勿扰 4离线

            userInfo.setOnline_status(2);
            apiUserService.update(userInfo);

            if (userInfo.getLive_price().compareTo(loginUser.getAvailable_amount()) > 0) {
                return R.ok(1, "余额不足", loginUser.getAvailable_amount());
            }
            apiUserService.recharge(loginUser, "del", userInfo.getLive_price());
            if (loginUser.getConnection() != null) {
                apiAmountBillService.connection(loginUser.getConnection(), userInfo.getLive_price().multiply(new BigDecimal(0.05)), loginUser.getId());
            }

            userInfo = apiUserService.queryObject(userInfo.getId());
            apiUserService.recharge(userInfo, "add", userInfo.getLive_price().multiply(new BigDecimal(0.5)));
            if (userInfo.getConnection() != null) {
                apiAmountBillService.connection(userInfo.getConnection(), userInfo.getLive_price().multiply(new BigDecimal(0.1)), userInfo.getId());
            }
        }

        ApiCallUserBillVo apiCallUserBillVo = new ApiCallUserBillVo();
        apiCallUserBillVo.setCreateTime(new Date());
        apiCallUserBillVo.setMode(mode);
        apiCallUserBillVo.setOrderId(orderId);
        apiCallUserBillVo.setAmount(userInfo.getLive_price());
        apiCallUserBillVo.setDialer(consumer);
        apiCallUserBillVo.setReceiver(tvAnchor);
        apiCallUserBillVo.setCallNo(callNo);
        apiCallUserBillVo.setStatus(1);
        apiCallUserBillService.save(apiCallUserBillVo);

        UserVo userVo = apiUserService.queryObject(loginUser.getId());

        return R.ok(0, "请求成功", userVo.getAvailable_amount().stripTrailingZeros().toPlainString());
    }


    /**
     * 插入通话记录
     *
     * @param loginUser
     * @param tvAnchor    接电话人
     * @param consumer    打电话人
     * @param mode        1拨出 2 接听
     * @param status      1接通 2未接通 3拒接
     * @param talkTime    通话时长
     * @param intimacy    亲密值
     * @param consumption 消费窝币
     * @return
     */
    @RequestMapping("/save")
    public R add(@LoginUser UserVo loginUser, Long tvAnchor, Long consumer, Integer mode, Long status, Long orderId,
                 @RequestParam(value = "talkTime", defaultValue = "0") Long talkTime,
                 @RequestParam(value = "intimacy", defaultValue = "0") BigDecimal intimacy,
                 @RequestParam(value = "consumption", defaultValue = "0") BigDecimal consumption, String callNo) {
        ApiOrderVo apiOrderVo = new ApiOrderVo();

        if (orderId != null) {
            apiOrderVo = apiOrderService.selectOne(orderId);
        }

        BigDecimal amount = new BigDecimal(0);

        if (status != null && status == 1L) {
            Long userId = tvAnchor;
            if (!loginUser.getId().equals(consumer)) {
                userId = consumer;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("callNo", callNo);
            List<ApiCallUserBillVo> userBillVos = apiCallUserBillService.selectList(params);

            /**
             * 通话市场
             */
            talkTime = (long) userBillVos.size();
            for (ApiCallUserBillVo info : userBillVos) {
                info.setStatus(2);
                amount = amount.add(info.getAmount());
                apiCallUserBillService.updata(info);
            }
            UserVo userVo = apiUserService.queryObject(userId);
            userVo.setOnline_status(1);

            apiUserService.update(userVo);
            //mouldName 1 live
            apiAmountBillService.consume(userId, "live", amount, loginUser);

            UserInfo zbUser = apiUserService.toUserInfo(tvAnchor, loginUser);

            apiOrderVo.setCreateDate(new Date());
            apiOrderVo.setStatus(3);
            apiOrderVo.setMouldId(userId);
            apiOrderVo.setMouldName("live");
            apiOrderVo.setCmUserId(consumer);
            apiOrderVo.setZbUserId(tvAnchor);
            apiOrderVo.setNum(1);
            apiOrderVo.setPrice(zbUser.getLivePrice());
            apiOrderVo.setTotal(amount);
            apiOrderVo.setCommentStatus(2);
            apiOrderService.save(apiOrderVo);
        }


        ApiCallBillVo info = new ApiCallBillVo();
        info.setCreateTime(new Date());
        info.setTvAnchor(tvAnchor);
        info.setConsumer(consumer);
        info.setMode(mode);
        info.setStatus(status);
        info.setTalkTime(talkTime);
        info.setIntimacy(amount);
        info.setConsumption(amount);
        apiCallBillService.save(info);
        return R.ok(0, "通话结束", apiOrderVo != null ? apiOrderVo : "");
    }
}
